package com.eascs.web.o2o.web.filter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.eascs.app.dao.SqlFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

/**
 * 数据权限过滤器
 * 
 * @author user
 *
 */
@Component
public class DataPermissionFilter implements SqlFilter {
	/** 权限关键字 */
	/// **DATA_PERMISSION(OL.LTD)**/
	private static final String DATA_PERMISSION_KEY = "DATA_PERMISSION";
	private static final String SQL_PATTERN_STR = "^.*\\/\\*\\*DATA_PERMISSION(\\([a-zA-Z0-9\\.\\_]+\\))\\*\\*\\/.*$";
	public static final Pattern SQL_PATTERN = Pattern.compile(SQL_PATTERN_STR);

	@Override
	public String filterSql(String sql) {
		User user = UserHolder.getUser();
		if (StringUtils.contains(sql, DATA_PERMISSION_KEY)) {
			Matcher mather = SQL_PATTERN.matcher(sql);
			if (mather.matches()) {
				String group1 = mather.group(1);
				String colum = StringUtils.substringBetween(group1, "(", ")");
				String permissionStr = StringUtils.replace(user.getDataPermissionStr(), "/**PERMISSION_COLUM**/",
						colum);
				String sqlStr = StringUtils.replace(sql, "/**DATA_PERMISSION" + group1 + "**/", permissionStr);
				return sqlStr;
			}

		}
		return sql;
	}

	public static void main(String[] args) {
		String str = " select count(1) from (select t.customer_id,t.customer_code,t.customer_name,"
				+ "t.mobile_number, t.id_number,t.customer_sd_name, t.customer_sd from customer_basic_info t where 1=1  "
				+ "and EXISTS (select 1 from customer_unit u where /**DATA_PERMISSION(u.unit_id)**/ u.customer_id = t.customer_id ) ) t__";
		Matcher mather = SQL_PATTERN.matcher(str);
		if (mather.matches()) {
			System.out.println(mather.group(1));
			String sqlStr = StringUtils.replace(str, "/**DATA_PERMISSION" + mather.group(1) + "**/", "xxxxx");
			System.out.println(sqlStr);
		}
	}
}
